//
//  ViewController.m
//  GPUImageTest
//
//  Created by akazam-wifi on 2017/1/11.
//  Copyright © 2017年 rjpan. All rights reserved.
//

#import "ViewController.h"
#import <GPUImage/GPUImage.h>

#define ScreenW [UIScreen mainScreen].bounds.size.width
#define ScreenH [UIScreen mainScreen].bounds.size.height

@interface ViewController ()

@property (nonatomic,strong)GPUImageBrightnessFilter *passthroughFilter;
@property (nonatomic,strong)UIImageView *imageView;

@property (nonatomic,strong)NSString *selectedType;                         //当前选中的滤镜类型
@property (nonatomic,strong)UIImage *sourceImage;                           //源图片
@property (nonatomic,strong)UISlider *slider;
@property (nonatomic,strong)NSArray *filterTitleArr;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.filterTitleArr = @[@"亮度",@"饱和度"];
    [self setupCustomImageView];
    [self setupCustomBtn];
    [self setupCustomSlider];
}

- (void)setupCustomSlider{
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(20, ScreenH -70, ScreenW -40, 20)];
    [self.slider addTarget:self action:@selector(sliderValueWasChangedWith:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.slider];
}



- (void)sliderValueWasChangedWith:(UISlider *)slider{
    float value = slider.value;
    
    if ([self.selectedType isEqualToString:@"亮度"]) {
        [self changeBrightnessFilterValueToPicetureWith:value];
    }
    else if ([self.selectedType isEqualToString:@"饱和度"]) {
        [self changeSaturationFilterValueToPicetureWith:value];
    }
}

- (void)changeSaturationFilterValueToPicetureWith:(float)value{
    
    UIImage *inputImage = self.sourceImage;
    
    //创建个饱和度的滤镜
    GPUImageSaturationFilter *saturationFilter = [[GPUImageSaturationFilter alloc]init];
    saturationFilter.saturation = value;
    
    //设置要渲染的区域
    [saturationFilter forceProcessingAtSize:inputImage.size];
    [saturationFilter useNextFrameForImageCapture];
    
    //获取数据源
    GPUImagePicture *stillImageSource = [[GPUImagePicture alloc]initWithImage:inputImage];
    
    //添加上滤镜
    [stillImageSource addTarget:saturationFilter];
    
    //开始渲染
    [stillImageSource processImage];
    
    //获取渲染后的图片
    UIImage *newImage = [saturationFilter imageFromCurrentFramebuffer];
    
    self.imageView.image = newImage;

}

/**
 改变亮度

 @param value 变动量
 */
- (void)changeBrightnessFilterValueToPicetureWith:(float)value{
    
    UIImage *inputImage = self.sourceImage;
    
    //创建一个亮度的滤镜
    self.passthroughFilter = [[GPUImageBrightnessFilter alloc] init];
    
    self.passthroughFilter.brightness = value;
    
    //设置要渲染的区域
    [self.passthroughFilter forceProcessingAtSize:inputImage.size];
    [self.passthroughFilter useNextFrameForImageCapture];
    
    //获取数据源
    GPUImagePicture *stillImageSource = [[GPUImagePicture alloc]initWithImage:inputImage];
    
    //添加上滤镜
    [stillImageSource addTarget:self.passthroughFilter];
    
    //开始渲染
    [stillImageSource processImage];
    
    //获取渲染后的图片
    UIImage *newImage = [self.passthroughFilter imageFromCurrentFramebuffer];
    
    self.imageView.image = newImage;
}



#pragma mark - 设置界面
- (void)setupCustomImageView{
    self.sourceImage = [UIImage imageNamed:@"111"];
    
    self.imageView = [[UIImageView alloc] initWithImage:self.sourceImage];
    
    self.imageView.frame = CGRectMake(0,0,ScreenW ,150);
    
    [self.view addSubview:self.imageView];
}

- (void)setupCustomBtn{
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, ScreenH -50, ScreenW, 40)];
    [btn setTitle:@"选择修改项" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor grayColor];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

- (void)btnClick:(UIButton *)btn{
    NSString *btnTitle = btn.titleLabel.text;
    
    if (![btnTitle isEqualToString:@"选择修改项"]) {
        [self writeImageToLocal:self.imageView.image];
        self.imageView.image = nil;
        
        NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        //现将图片保存到本地
        NSString *imagePath = [NSString stringWithFormat:@"%@/123.png",filePath];
        
        self.sourceImage = [UIImage imageWithContentsOfFile:imagePath];
        
        self.imageView.image = self.sourceImage;
    }
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"选择修改项" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (int i = 0; i<self.filterTitleArr.count; i++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:self.filterTitleArr[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.selectedType = action.title;
            [btn setTitle:action.title forState:UIControlStateNormal];
            [self changeSliderMaxAndMinValueWith:action.title];
        }];
        [alertController addAction:action];
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];

}

- (void)changeSliderMaxAndMinValueWith:(NSString *)type{
    if ([type isEqualToString:@"亮度"]) {
        self.slider.maximumValue = 1;
        self.slider.minimumValue = -1;
        self.slider.value = 0;
    }
    else if ([type isEqualToString:@"饱和度"]) {
        self.slider.maximumValue = 10;
        self.slider.minimumValue = -10;
        self.slider.value = 0;
    }
}

/**
 使用滤镜渲染单张图片
 */
- (void)processOneImage{
    UIImage *inputImage = [UIImage imageNamed:@"111"];
    
    //创建一个亮度的滤镜
    self.passthroughFilter = [[GPUImageBrightnessFilter alloc] init];
    
    self.passthroughFilter.brightness = 0.3f;
    
    //设置要渲染的区域
    [self.passthroughFilter forceProcessingAtSize:inputImage.size];
    [self.passthroughFilter useNextFrameForImageCapture];
    
    //获取数据源
    GPUImagePicture *stillImageSource = [[GPUImagePicture alloc]initWithImage:inputImage];
    
    //添加上滤镜
    [stillImageSource addTarget:self.passthroughFilter];
    
    //开始渲染
    [stillImageSource processImage];
    
    //获取渲染后的图片
    UIImage *newImage = [self.passthroughFilter imageFromCurrentFramebuffer];
    
    //加载出来
    self.imageView = [[UIImageView alloc] initWithImage:newImage];
    
    self.imageView.frame = CGRectMake(0,0,ScreenW ,150);
    
    [self.view addSubview:self.imageView];
    
}

/**
 组合滤镜渲染图片
 */
- (void)processImageWithGoroupFilter{
    UIImage *inputImage = [UIImage imageNamed:@"111"];
    
    //创建一个亮度的滤镜
    GPUImageBrightnessFilter *passthroughFilter = [[GPUImageBrightnessFilter alloc] init];
    
    passthroughFilter.brightness = 0.3f;

     //创建个饱和度的滤镜
     GPUImageSaturationFilter *saturationFilter = [[GPUImageSaturationFilter alloc]init];
     saturationFilter.saturation = 2.5f;
    
    //创建混合渲染图片
    GPUImagePicture *picture  = [[GPUImagePicture alloc] initWithImage:inputImage smoothlyScaleOutput:YES];
    
     //创建返回视图的view
     GPUImageView *gpuView = [[GPUImageView alloc]initWithFrame:CGRectMake(0, 300, ScreenW ,200)];
     gpuView.fillMode = kGPUImageFillModeStretch;
     [self.view addSubview:gpuView];
     //传入滤镜数组，输入图片源（GPUImagePicture），返回视图（GPUImageView）
     GPUImageFilterPipeline *pipLine = [[GPUImageFilterPipeline alloc]initWithOrderedFilters:@[passthroughFilter,saturationFilter] input:picture output:gpuView];
     //渲染原图
     [picture processImage];
}

/**
 将图片保存到本地
 
 @param image 要保存的图片
 */
- (void)writeImageToLocal:(UIImage *)image{
    //保存图片
    NSData *imageData = UIImagePNGRepresentation(image);
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //现将图片保存到本地
    NSString *imagePath = [NSString stringWithFormat:@"%@/123.png",filePath];
    [imageData writeToFile:imagePath atomically:YES];
    
    NSLog(@"%@",filePath);
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
